/*
 * Copyright (c) 2009 Sun Microsystems, Inc.
 * Copyright (c) 2011 Oracle Corporation.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 **/

package com.sun.spot.wot.gateway;

import java.util.logging.Level;
import java.util.logging.Logger;
import com.sun.spot.wot.http.HttpResponse;

/**
 *
 * @author vgupta
 */
public class PendingRequestHandler extends Thread {
    Device dev = null;
    boolean done = false;

    PendingRequestHandler(Device dev) {
        this.dev = dev;
    }

    public void markDone() {
        done = true;
    }

    public void run() {
//        System.out.println("Starting pendingRequest handler for device " +
//                dev.getId());

        while (!done) {
            // get next unsatisfied request and handle it
//            synchronized (dev) {
                RequestQueueEntry rqe = dev.getRequestQueue().getNextPendingEntry();
                if (rqe != null) {
//                    System.out.println("Handling pending request ..." + rqe);
                    while (dev.isSleeping()) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(PendingRequestHandler.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    };
                    HttpResponse res = dev.getDeviceResponse(rqe.getRequest());
                    if (res.getStatus() != HttpResponse.SC_INTERNAL_SERVER_ERROR) {
                        dev.getRequestQueue().markComplete(rqe.getRequestId(),
                                res);
                    } else {
                        // device is probably sleeping
                        long waitPeriod = dev.getRemainingSleepDuration();
                        if (waitPeriod <= 0) {
                            waitPeriod = 0;
                            System.out.println("Adjusted wait period to 0");
                        }
                        System.err.println("Error communicating with device " +
                                dev.getId() + ", pausing for " +
                                waitPeriod + " ...");
                        try {
                            Thread.sleep(waitPeriod);
//
//                        try {
//                            dev.wait(waitPeriod);
//                            System.out.println("Thread for device " +
//                                    dev.getId() + " resuming ...");
//                        } catch (InterruptedException ex) {
//                            Logger.getLogger(PendingRequestHandler.class.getName()).log(Level.SEVERE, null, ex);
//                        }
                        } catch (InterruptedException ex) {
                            Logger.getLogger(PendingRequestHandler.class.getName()).log(Level.SEVERE, null, ex);
                        }
//


//                        try {
//                            dev.wait(waitPeriod);
//                            System.out.println("Thread for device " +
//                                    dev.getId() + " resuming ...");
//                        } catch (InterruptedException ex) {
//                            Logger.getLogger(PendingRequestHandler.class.getName()).log(Level.SEVERE, null, ex);
//                        }
                    }
                } else {
//                    System.out.println("No pending entry for device " +
//                            dev.getId() + ", pausing ...");
//                    try {
//                        dev.wait();
//                        System.out.println("Thread for device " +
//                                dev.getId() + " resuming ...");
//                    } catch (InterruptedException ex) {
//                        Logger.getLogger(PendingRequestHandler.class.getName()).log(Level.SEVERE, null, ex);
//                    }
                }
            try {
//            }
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(PendingRequestHandler.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

}
